﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using SqlSugar.SplitTableExtensions;
using System.Data;
using System.Numerics;

namespace ProjectScheduling
{
    public partial class WarnOperatorForm : Form
    {
        public readonly static WarnOperatorForm b = new();
        readonly ProjectDao dao = ProjectDao.Base;
        private WarnOperatorForm()
        {
            InitializeComponent();
        }
        public Action? action;
        // 确认操作
        private bool CheckOk(string msg) => MessageBox.Show(msg, "操作确认", MessageBoxButtons.YesNo) == DialogResult.Yes;

        public void Init(int id, int state, int rate = 0)
        {
            p_main.Controls.Clear();
            void btn(string text, Func<bool> act)
            {
                var len = p_main.Controls.Count;
                var per = p_main.Width / 4;

                var _btn = new Button
                {
                    Text = text,
                    Location = new Point(per * len, 5),
                };
                _btn.Click += (o, e) =>
                {
                    if (act())
                    {
                        action?.Invoke();
                        Close();
                    }
                };
                p_main.Controls.Add(_btn);
            }
            void UpdateHistory(Action act)
            {
                var project = ProjectDao.Base.Find(id);
                if (project == null) return;
                var form = new Form
                {
                    Text = "信息确认",
                    Width = 600,
                    Height = 300,
                    StartPosition = FormStartPosition.CenterParent
                };
                var dg = new DataGridView
                {
                    Size = new Size(550, 200),
                    Location = new Point(25, 10),
                    Dock = DockStyle.Top
                };
                var staffs = StaffDao.Base.FindAll(it => true);
                {

                    dg.Columns.Add(new DataGridViewComboBoxColumn
                    {
                        HeaderText = "施工人",
                        DataPropertyName = "StaffId",
                        Name = "StaffId",
                        DataSource = staffs,
                        ValueMember = "Id",
                        DisplayMember = "TrueName",
                        ReadOnly = false
                    });
                    dg.Columns.Add(new DataGridViewTextBoxColumn
                    {
                        HeaderText = "开始日期",
                        DataPropertyName = "StartDate",
                        Name = "StartDate",
                        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                        Width = 150
                    });
                    dg.Columns.Add(new DataGridViewTextBoxColumn
                    {
                        HeaderText = "结束日期",
                        DataPropertyName = "EndDate",
                        Name = "EndDate",
                        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                        Width = 150
                    });
                    dg.Columns.Add(new DataGridViewTextBoxColumn
                    {
                        HeaderText = "个人投入工时天",
                        DataPropertyName = "Days",
                        Name = "Days",
                        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                        Width = 60
                    });
                    dg.Columns.Add(new DataGridViewButtonColumn
                    {
                        HeaderText = "删除",
                        Text = "删除",
                        UseColumnTextForButtonValue = true,
                        Width = 80
                    });
                    ProjectStaffDao.Base.FindAll(it => it.ProjectId == id).ForEach(it =>
                    {

                        dg.Rows.Add(it.UserId, project.FromDate.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), (DateTime.Today - project.FromDate.Date).TotalDays + 1);
                    });
                    dg.CellEndEdit += (o, e) =>
                    {
                        if (e.RowIndex < 0) return;
                        var row = dg.Rows[e.RowIndex];
                        var st = row.Cells["StartDate"].Value as string;
                        var ed = row.Cells["EndDate"].Value as string;
                        if (!string.IsNullOrEmpty(st) && !string.IsNullOrEmpty(ed))
                        {
                            if (DateTime.TryParse(st, out DateTime st1) && DateTime.TryParse(ed, out DateTime ed1))
                            {
                                row.Cells["Days"].Value = (ed1 - st1).TotalDays + 1;
                            }
                        }
                    };
                    dg.CellContentClick += (o, e) =>
                    {
                        if (e.RowIndex < 0) return;
                        if (e.ColumnIndex == 4)
                        {
                            dg.Rows.RemoveAt(e.RowIndex);
                        }
                    };
                }
                form.Controls.Add(dg);
                {
                    var okBtn = new Button
                    {
                        Text = "提交",
                        Location = new Point(280, 220),

                    };
                    form.Controls.Add(new Label
                    {
                        Location = new Point(30, 220),
                        AutoSize = true,
                        Text = "工作量评分："
                    });
                    var scoreTxt = new TextBox
                    {
                        Text = "",
                        Location = new Point(110, 217),
                        Size = new Size(100, 25)
                    };
                    form.Controls.Add(scoreTxt);
                    okBtn.Click += (o, e) =>
                    {
                        if (project == null) return;
                        var score = (scoreTxt.Text?.Trim()) ?? "";
                        if (string.IsNullOrEmpty(score) || !int.TryParse(score, out int _))
                        {
                            MessageBox.Show("请填写工作量评分");
                            return;
                        }

                        var list = new List<PreparedStaff>();
                        foreach (DataGridViewRow row in dg.Rows.Cast<DataGridViewRow>())
                        {
                            string vlue(string key)
                            {
                                var dta = row.Cells[key].Value?.ToString() ?? "";
                                return dta;
                            }
                            if (!int.TryParse(vlue("StaffId"), out int _x)) continue;
                            var staff = staffs.Find(z => z.Id == Convert.ToInt32(vlue("StaffId")));
                            bool isDate(string key)
                            {
                                return DateTime.TryParse(vlue(key), out DateTime dt);
                            }
                            if (!isDate("StartDate"))
                            {
                                MessageBox.Show($"请确认 {staff?.TrueName ?? ""} 的开始日期");
                                return;
                            }
                            if (!isDate("EndDate"))
                            {
                                MessageBox.Show($"请确认 {staff?.TrueName ?? ""} 的结束日期");
                                return;
                            }

                            list.Add(new PreparedStaff
                            {
                                StaffId = staff?.Id ?? 0,
                                Content = new PrepardStaffContent
                                {
                                    FromDate = Convert.ToDateTime(vlue("StartDate")),
                                    ToDate = Convert.ToDateTime(vlue("EndDate")),
                                    ProjectId = project?.Id ?? 0,
                                    ProjectName = project?.Name,
                                    StaffName = staff?.TrueName
                                },
                                Days = Convert.ToInt32(vlue("Days"))
                            });
                        }
                        if (list.Count == 0)
                        {
                            MessageBox.Show("提交信息为空");
                            return;
                        }
                        var preData = new PreparedData
                        {
                            CreateTime = DateTime.Now,
                            ProjectId = project?.Id ?? 0,
                            Days = list.Sum(z => z.Days),
                            FromDate = list.Min(z => z?.Content?.FromDate ?? DateTime.MinValue),
                            ToDate = list.Max(z => z.Content?.ToDate ?? DateTime.Today),
                            Id = 0
                        };
                        // 开始保存数据
                        var pid = PreparedDataDao.Base.Add(preData);
                        list.ForEach(z =>
                        {
                            z.PreparedId = pid;
                        });
                        project.Score = int.Parse(score);
                        project.StaffDays += list.Sum(z => z.Days);
                        ProjectDao.Base.Update(project, it => new { it.StaffDays, it.Score });
                        PreparedStaffDao.Base.AddRange(list);
                        act.Invoke();
                        form.Close();
                    };
                    form.Controls.Add(okBtn);
                }
                form.ShowDialog();
            }
            //void UpdateHistory(Action act)
            //{
            //    var project = ProjectDao.Base.Find(id);
            //    if (project == null) return;
            //    var form = new Form
            //    {
            //        Text = "信息确认",
            //        Width = 350,
            //        Height = 250,
            //        StartPosition = FormStartPosition.CenterParent
            //    };
            //    form.Controls.Add(new Label
            //    {
            //        Location = new Point(30, 33),
            //        Text = "实际开始",
            //        AutoSize = true,
            //    });
            //    form.Controls.Add(new Label
            //    {
            //        Location = new Point(30, 73),
            //        Text = "实际结束",
            //        AutoSize = true
            //    });
            //    form.Controls.Add(new Label
            //    {
            //        Location = new Point(30, 113),
            //        Text = "施工天数",
            //        AutoSize = true
            //    });
            //    var txt_start = new DateTimePicker
            //    {
            //        Location = new Point(100, 30),
            //        Size = new Size(200, 20),
            //        CustomFormat = "yyyy-MM-dd日HH时",
            //        Format = DateTimePickerFormat.Custom,
            //        Value = project.FromDate
            //    };
            //    var txt_end = new DateTimePicker
            //    {
            //        Location = new Point(100, 70),
            //        Size = new Size(200, 20),
            //        CustomFormat = "",
            //        Format = DateTimePickerFormat.Custom,
            //        Value = project.ToDate
            //    };

            //    txt_end.ValueChanged += (o, e) =>
            //    {
            //        txt_end.CustomFormat = "yyyy-MM-dd日HH时";
            //    };
            //    var txt_days = new TextBox
            //    {
            //        Location = new Point(100, 110),
            //        Size = new Size(200, 20),
            //        Text = ((project.ToDate - project.FromDate).Days + 1).ToString()
            //    };
            //    var btn_save = new Button
            //    {
            //        Location = new Point(120, 150),
            //        Size = new Size(100, 30),
            //        Text = "确认保存"
            //    };
            //    btn_save.Click += (o, e) =>
            //    {
            //        var staffs = ProjectStaffDao.Base.FindAll(it => it.ProjectId == id);
            //        if (staffs.Count == 0)
            //        {
            //            MessageBox.Show("获取施工人员信息有误");
            //            return;
            //        }
            //        if (txt_end.CustomFormat == "")
            //        {
            //            MessageBox.Show("请选择结束日期");
            //            return;
            //        }
            //        if (string.IsNullOrEmpty(txt_days.Text))
            //        {
            //            MessageBox.Show("请输入施工天数");
            //            return;
            //        }
            //        var pid = PreparedDataDao.Base.Add(new PreparedData
            //        {
            //            Days = Convert.ToInt32(txt_days.Text),
            //            FromDate = txt_start.Value,
            //            ToDate = txt_end.Value,
            //            CreateTime = DateTime.Now,
            //            ProjectId = id,
            //        });
            //        staffs.Select(it => new PreparedStaff
            //        {
            //            PreparedId = pid,
            //            StaffId = it.UserId,
            //            Days = Convert.ToInt32(txt_days.Text),
            //            Content = new PrepardStaffContent
            //            {
            //                FromDate = txt_start.Value,
            //                ToDate = txt_end.Value,
            //                ProjectId = id,
            //                ProjectName = project.Name,
            //                StaffName = it.UserName
            //            }
            //        }).ToList().
            //        ForEach(it => PreparedStaffDao.Base.Add(it));
            //        project.StaffDays += staffs.Count * Convert.ToInt32(txt_days.Text);
            //        ProjectDao.Base.Update(project, it => new { it.StaffDays });
            //        act.Invoke();
            //        form.Close();
            //    };
            //    form.Controls.AddRange([txt_start, txt_end, txt_days, btn_save]);
            //    form.ShowDialog();
            //}

            switch (state)
            {
                case 0:
                    btn("退回重排期", () =>
                    {
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (!CheckOk("是否确认退回重排期…")) return false;
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        dao.Update(new Projects
                        {
                            Id = id,
                            State = Enum_ProjectState.待排期,
                            Rate = 0
                        }, it => new { it.State, it.Rate });
                        StateRecordDao.Base.Add(new()
                        {
                            ProjectId = id,
                            CreateTime = DateTime.Now,
                            Record = "返回重排期",
                            Remark = remark
                        });
                        return true;
                    });
                    btn("实施中", () =>
                    {
                        if (!CheckOk("是否确认项目实施中…")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        dao.Update(new Projects
                        {
                            Id = id,
                            State = Enum_ProjectState.实施中
                        }, it => new { it.State });
                        StateRecordDao.Base.Add(new()
                        {
                            ProjectId = id,
                            CreateTime = DateTime.Now,
                            Record = "状态更新为实施中",
                            Remark = remark
                        });
                        return true;
                    });
                    btn("已完结", () =>
                    {
                        if (!CheckOk("是否确认退项目已完成")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        UpdateHistory(() =>
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                State = Enum_ProjectState.已完结,
                                Rate = 100
                            }, it => new { it.State, it.Rate });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = "状态更新为已完结",
                                Remark = remark
                            });
                            action?.Invoke();
                            Close();
                        });

                        return false;
                    });
                    lb_2.Visible = p_state.Visible = false;
                    break;
                case 1:
                    ComboBox txt_rate = new ComboBox
                    {
                        Width = 90
                    };
                    txt_rate.Items.AddRange(["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]);
                    txt_rate.SelectedIndex = (rate / 10);
                    btn("退回重排期", () =>
                    {
                        if (!CheckOk("是否确认退回重排期")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        dao.Update(new Projects
                        {
                            Id = id,
                            State = Enum_ProjectState.待排期,
                            Rate = 0
                        }, it => new { it.State, it.Rate });
                        StateRecordDao.Base.Add(new()
                        {
                            ProjectId = id,
                            CreateTime = DateTime.Now,
                            Record = "退回重排期",
                            Remark = remark
                        });
                        return true;
                    });
                    btn("已完结", () =>
                    {
                        if (!CheckOk("是否确认项目已完结")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        UpdateHistory(() =>
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                State = Enum_ProjectState.已完结,
                                Rate = 100
                            }, it => new { it.State, it.Rate });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = "状态更新为已完结",
                                Remark = remark
                            });
                            action?.Invoke();
                            Close();
                        });

                        return false;
                    });
                    btn("挂起暂停", () =>
                    {
                        if (!CheckOk("是否确认项目挂起暂停")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        UpdateHistory(() =>
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                State = Enum_ProjectState.挂起
                            }, it => new { it.State });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = "状态更新为挂起暂停",
                                Remark = remark
                            });
                            action?.Invoke();
                            Close();
                        });

                        return false;
                    });
                    lb_2.Visible = p_state.Visible = true;
                    lb_2.Text = "进度";
                    var btn1 = new Button
                    {
                        Text = "更新进度",
                        Location = new Point(100, 0)
                    };
                    btn1.Click += (o, e) =>
                    {
                        if (!CheckOk("是否确认更新项目进度")) return;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return;
                        }
                        var rate = Convert.ToInt32(txt_rate.Text.Replace("%", ""));
                        void func()
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                Rate = rate,
                                State = (rate < 100) ? Enum_ProjectState.实施中 : Enum_ProjectState.已完结,
                            }, it => new { it.Rate, it.State });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = $"更新进度为{rate}%",
                                Remark = remark
                            });
                            action?.Invoke();
                            Close();
                        }
                        switch (rate)
                        {
                            case < 100:
                                func();
                                break;
                            default:
                                UpdateHistory(func);
                                break;
                        }
                    };
                    p_state.Controls.Clear();
                    p_state.Controls.Add(txt_rate);
                    p_state.Controls.Add(btn1);
                    break;
                case 2:
                    var txt_time = new DateTimePicker
                    {
                        Value = DateTime.Today.AddHours(DateTime.Now.Hour + 1),
                        MinDate = DateTime.Today,
                        Format = DateTimePickerFormat.Custom,
                        CustomFormat = "yyyy-MM-dd日HH时",
                        Width = 160
                    };
                    btn("退回重排期", () =>
                    {
                        if (!CheckOk("是否确认退回重排期")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        dao.Update(new Projects
                        {
                            Id = id,
                            State = Enum_ProjectState.待排期,
                            Rate = 0
                        }, it => new { it.State, it.Rate });
                        StateRecordDao.Base.Add(new()
                        {
                            ProjectId = id,
                            CreateTime = DateTime.Now,
                            Record = "退回重排期",
                            Remark = remark,
                        });
                        return true;
                    });
                    btn("已完结", () =>
                    {
                        if (!CheckOk("是否确认项目已完结")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        UpdateHistory(() =>
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                State = Enum_ProjectState.已完结,
                                Rate = 100
                            }, it => new { it.State, it.Rate });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = "状态更新为已完结",
                                Remark = remark,
                            });
                            action?.Invoke();
                            Close();
                        });
                        return false;
                    });
                    btn("挂起暂停", () =>
                    {
                        if (!CheckOk("是否确认项目挂起暂停")) return false;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return false;
                        }
                        UpdateHistory(() =>
                        {
                            dao.Update(new Projects
                            {
                                Id = id,
                                State = Enum_ProjectState.挂起
                            }, it => new { it.State });
                            StateRecordDao.Base.Add(new()
                            {
                                ProjectId = id,
                                CreateTime = DateTime.Now,
                                Record = "状态更新为挂起",
                                Remark = remark,
                            });
                            action?.Invoke();
                            Close();
                        });
                        return false;
                    });
                    lb_2.Text = "延时时间";
                    lb_2.Visible = p_state.Visible = true;
                    p_state.Controls.Clear();
                    p_state.Controls.Add(txt_time);
                    var btn3 = new Button
                    {
                        Text = "延时",
                        Location = new Point(180, 0)
                    };
                    btn3.Click += (o, e) =>
                    {

                        if (txt_time.Value < DateTime.Now)
                        {
                            MessageBox.Show("延时结束时间不能早于当前时间");
                            return;
                        }
                        if (!CheckOk("是否确认项目要延时")) return;
                        var remark = txt_remark.Text?.Trim() ?? "";
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("备注不能为空");
                            return;
                        }
                        dao.Update(new Projects
                        {
                            Id = id,
                            ToDate = txt_time.Value
                        }, it => new { it.ToDate });
                        StateRecordDao.Base.Add(new()
                        {
                            ProjectId = id,
                            CreateTime = DateTime.Now,
                            Record = $"延时结束时间为：{txt_time.Value:MM-dd}",
                            Remark = remark,
                        });
                        action?.Invoke();
                        Close();
                    };
                    p_state.Controls.Add(btn3);
                    break;
            }
        }

    }
}
